package com.myprocessing.gui.util.spring;

import java.beans.PropertyEditorSupport;

import org.springframework.util.StringUtils;

import com.myprocessing.gui.util.Coord;

public class CustomCoordEditor extends PropertyEditorSupport {

	private final boolean allowEmpty;

	public CustomCoordEditor(boolean allowEmpty) {
		this.allowEmpty = allowEmpty;
	}

	public void setAsText(String text) throws IllegalArgumentException {
		if (this.allowEmpty && !StringUtils.hasText(text)) {
			// Treat empty String as null value.
			setValue(null);
		} else if (text != null && text.length() < 4 && text.length() > 10) {
			throw new IllegalArgumentException(
					"Could not parse Coord: it is not between 4 and 10 characters long");
		} else {
			try {
				String[] split = text.split("x|, ?");
				Coord coord = new Coord(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
				setValue(coord);
			} catch (Exception ex) {
				IllegalArgumentException iae = new IllegalArgumentException(
						"Could not parse String: " + ex.getMessage());
				iae.initCause(ex);
				throw iae;
			}
		}
	}
	
	public String getAsText() {
		Coord coord = (Coord) getValue();
		return (coord != null ? coord.toString() : "");
	}

}
